<template>
	<view class="supermarketPage">
		<!-- 商品详情 -->
		<goods-list :goods="goods" @goGoodsDetail="goGoodsDetail" />
	</view>
</template>

<script>
	import goodsList from "@/components/goods-list.vue";
	export default {
		name: "supermarket",
		components: {
			goodsList
		},
		onLoad(option) {
			this.getOpenerEventChannel().on('indexPage', res => {
				this.goods = res.data;
				// 获取商品列表总数
				this.total = res.total;
				// 从第几条数据开始
				this.skip = res.data.length;
			});
		},
		data() {
			return {
				// 商品数量
				goods: [],
				// 设置页面获取的数据量
				limit: 6,
				// 跳过多少条数据量
				skip: void 0,
				// 商品列表总数
				total: void 0,
				// 是否显示触底(数据已经加载完了)
				flag: false
			};
		},
		methods: {
			async getGoods(callback) {
				let res = await uniCloud.callFunction({
					name: 'goods',
					data: {
						methods: "get",
						limit: this.limit,
						skip: this.skip,
					}
				});
				// 商品列表
				this.goods = [...this.goods, ...res.result.data.data];
				this.skip = this.skip + this.limit;

				// 判断是否有回调函数，若有则执行它
				callback && callback();
			},

			// 跳转到导航的商品详情页
			goGoodsDetail(item) {
				uni.navigateTo({
					url: "../goodsDetail/goodsDetail",
					success: res => {
						res.eventChannel.emit('goodsDetail', {
							item
						});
					}
				});
			},
		},
		// 触底加载
		onReachBottom() {
			if (this.goods.length < this.total) {
				this.getGoods();
			} else {
				this.flag = true;
			};
		},
		// 下拉刷新
		onPullDownRefresh() {
			if (this.goods.length < this.total) {
				this.getGoods(() => {
					uni.stopPullDownRefresh();
				});
			} else {
				uni.stopPullDownRefresh();
				uni.showToast({
					title: `已经没有更多了`,
					icon: "none",
				});
			};
		},
	}
</script>

<style lang="scss">
	.supermarketPage {
		padding: 10rpx 0;
		background-color: #eee;
	}
</style>
